package com.medical.literature.recognition.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.medical.literature.common.vo.Result;
import com.medical.literature.recognition.dto.RecognitionRequest;
import com.medical.literature.recognition.dto.RecognitionResult;
import com.medical.literature.recognition.service.RecognitionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 识别控制器
 */
@Slf4j
@RestController
@RequestMapping("/recognition")
@RequiredArgsConstructor
public class RecognitionController {
    
    private final RecognitionService recognitionService;

    /**
     * 启动识别任务
     */
    @PostMapping("/start")
    public Result<Long> startRecognition(@Valid @RequestBody RecognitionRequest request) {
        log.info("收到启动识别任务请求: literatureId={}, fileType={}, recognitionType={}", 
            request.getLiteratureId(), request.getFileType(), request.getRecognitionType());
        Long taskId = recognitionService.startRecognitionTask(request);
        log.info("识别任务启动成功，任务ID: {}", taskId);
        return Result.success("识别任务启动成功", taskId);
    }

    /**
     * 获取识别任务状态
     */
    @GetMapping("/status/{taskId}")
    public Result<RecognitionResult> getRecognitionStatus(@PathVariable Long taskId) {
        log.info("收到获取识别任务状态请求，任务ID: {}", taskId);
        RecognitionResult result = recognitionService.getRecognitionStatus(taskId);
        log.info("获取识别任务状态完成，任务ID: {}, 状态: {}", taskId, result != null ? result.getStatus() : "null");
        return Result.success(result);
    }

    /**
     * 直接处理识别（同步）
     */
    @PostMapping("/process")
    public Result<RecognitionResult> processRecognition(@Valid @RequestBody RecognitionRequest request) {
        log.info("收到识别请求: literatureId={}, filePath={}, fileType={}, recognitionType={}", 
            request.getLiteratureId(), request.getFilePath(), request.getFileType(), request.getRecognitionType());
        
        // 添加更多日志来诊断请求
        log.debug("完整识别请求对象: {}", request);
        
        try {
            RecognitionResult result = recognitionService.processRecognition(request);
            
            log.info("识别处理完成: literatureId={}, status={}, textLength={}, keywordsCount={}", 
                result.getLiteratureId(), result.getStatus(), 
                result.getTextContent() != null ? result.getTextContent().length() : 0,
                result.getKeywords() != null ? result.getKeywords().size() : 0);
            
            Result<RecognitionResult> response = Result.success(result);
            log.info("返回响应: code={}, message={}, data is null={}", 
                response.getCode(), response.getMessage(), response.getData() == null);
            
            // 添加调试日志，查看返回的JSON格式
            try {
                ObjectMapper mapper = new ObjectMapper();
                mapper.registerModule(new JavaTimeModule());
                String jsonResponse = mapper.writeValueAsString(response);
                log.debug("返回的JSON响应: {}", jsonResponse);
            } catch (Exception e) {
                log.error("序列化响应对象时出错: {}", e.getMessage(), e);
            }
            
            return response;
        } catch (Exception e) {
            log.error("处理识别请求时发生异常: {}", e.getMessage(), e);
            return Result.error("识别处理失败: " + e.getMessage());
        }
    }
}